package cn.edu.gduf.luowowo.website.web.resolver;

import cn.edu.gduf.luowowo.cache.service.IUserInfoRedisService;
import cn.edu.gduf.luowowo.member.domain.UserInfo;
import cn.edu.gduf.luowowo.website.annotation.UserParam;
import cn.edu.gduf.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserInfoResolver implements HandlerMethodArgumentResolver{
    @Reference
    private IUserInfoRedisService redisService;
    /**
     * 是否支持该参数
     * @param parameter 理解为请求映射方法中的形参
     * @return true表示对该参数进行解析，并设置属性
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == UserInfo.class
                && parameter.hasParameterAnnotation(UserParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getToken(request);
        return redisService.getUserByToken(token);
    }
}
